package main

import (
	"MqttCloudProtocolServer/LogTools/config"
	"MqttCloudProtocolServer/publiclib/define"
	"MqttCloudProtocolServer/publiclib/helplib"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/wonderivan/logger"
)

func main() {
	logInit()
	logger.Debug("Start LogTools")
	cfg := config.LoadCfg(define.ConfigPath + "logtools.json")
	if cfg == nil {
		logger.Error("LoadCfg failed")
		return
	}
	go mqttListen(cfg)
	var cmdLine string
	for strings.ToUpper(cmdLine) != "EXIT" {
		fmt.Scanln(&cmdLine)
		time.Sleep(time.Second)
	}
}
func mqttListen(cfg *config.ConfigModel) {

	addr := "tcp://" + cfg.Host + ":" + strconv.Itoa((int)(cfg.Port))
	//subStrings := [2]string{"PM515-highde-cloud", "PM515-highde-gateway"}

	var mqttClient mqtt.Client
	//connect mqtt-server and set clientID
	opts := mqtt.NewClientOptions().AddBroker(addr).SetClientID("ListenerToolsRemote")

	//set userName
	opts.SetUsername(cfg.User)
	opts.SetPassword(cfg.Password)
	opts.SetKeepAlive(2 * time.Second)
	opts.SetPingTimeout(2 * time.Second)
	opts.SetConnectRetryInterval(time.Second * 2)
	opts.SetConnectRetry(true)
	opts.SetAutoReconnect(true)
	opts.SetMaxReconnectInterval(time.Second * 2)
	opts.SetOnConnectHandler(func(cc mqtt.Client) {
		//fmt.Println("ListenerTools" + ": Connect")
		logger.Warn("ListenerTools" + ": Connect")
		mqttClient = cc
		//subscribe topic
		for _, topic := range cfg.Topics {
			var handel func(client mqtt.Client, message mqtt.Message)
			switch topic.Format {
			case "string":
				handel = getMessageHandlerHex
			case "hex":
				handel = getMessageHandlerStr
			default:
				logger.Alert(topic.Topic + ":topic.Format error")
				continue
			}
			if token := mqttClient.Subscribe(topic.Topic, 0, handel); token.Error() != nil {
				//fmt.Println("token.Error()")
				logger.Alert("token.Error()")
				logger.Alert(token.Error().Error())
				token.Wait()
				//os.Exit(1)
			}
		}
	})
	opts.SetConnectionLostHandler(func(_ mqtt.Client, _ error) {
		mqttClient = nil
		//fmt.Println("ListenerTools" + ": LostConnect")
		logger.Warn("ListenerTools" + ": LostConnect")
	})

	opts.SetReconnectingHandler(func(_ mqtt.Client, _ *mqtt.ClientOptions) {
		//fmt.Println("ListenerTools" + ": ReConnect")
		logger.Warn("ListenerTools" + ": ReConnect")
	})
	//create object
	mqttClient = mqtt.NewClient(opts)
	mqttClient.Connect()
	mqttClient = nil
}
func getMessageHandlerHex(client mqtt.Client, message mqtt.Message) {
	content := helplib.BufferToString(message.Payload())
	getMessageHandler(client, message, content)
}
func getMessageHandlerStr(client mqtt.Client, message mqtt.Message) {
	content := helplib.BufferToString(message.Payload())
	getMessageHandler(client, message, string(content))
}
func getMessageHandler(client mqtt.Client, message mqtt.Message, content string) {
	//fmt.Println("ListenerTools" + ",Topic: " + message.Topic() + ",Message: " + payload)
	if client == nil {
		logger.Warn("mqttClient is nil")
	}
	logger.Warn("ListenerTools" + ",Topic: " + message.Topic() + ",Message: " + content)
}
func logInit() {
	// change to current dir
	if path, err := os.Executable(); err != nil {
		logger.Fatal(err)
	} else {
		logger.Info(path)
		appPath := filepath.Dir(path)
		logger.Info(appPath)
		if err := os.Chdir(appPath); err != nil {
			logger.Fatal(err)
		}
		define.InitInternalPath()
		define.CheckIsLog("logtools.log")
		//isrunning = true
	}
}
